<template>
  <div class="star">
    <el-table
        :data="
        tableData.filter(
          (data) =>
            !search || data.fname.toLowerCase().includes(search.toLowerCase())
        )"
        style="width: 100%"
      highlight-current-row
      show-header
      @selection-change="handleSelectionChange">
      <el-table-column  type="selection" width="55"> </el-table-column>
      <el-table-column prop="fid" label="ID" width="80"></el-table-column>
      <el-table-column
        prop="fname"
        label="鲜花名称"
        width="100"
      ></el-table-column>
      <el-table-column label="鲜花进价" width="90">
        <template slot-scope="scope">
          ￥{{scope.row.mprice}}
        </template>
      </el-table-column>
      <el-table-column label="鲜花售价" width="90">
        <template slot-scope="scope">
          ￥{{scope.row.sprice}}
        </template>
      </el-table-column>
      <el-table-column  align="center" label="图片" width="80">
        <template slot-scope="scope">

          <img
            :src="require(`../../assets/${scope.row.img}`)"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>

      <el-table-column align="center"  prop="fdesc" label="描述" width="250"></el-table-column>
      <el-table-column align="center" prop="tname" label="类型" width="100"></el-table-column>
      <el-table-column prop="obj" label="赠送对象" width="100"></el-table-column>
      <el-table-column prop="cnt" label="库存量" width="80"></el-table-column>
      <el-table-column align="right">
        <template slot="header">
          <el-input v-model="search" size="mini" placeholder="输入鲜花类型搜索您想要的东西" />
        </template>
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="primary"
              @click="displayUpdate(scope.row)"
          >修改</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
 
    <div class="footer">
    <div class="elbutton">
      <el-button type="success" plain size="small" @click="add">新增</el-button>
      <el-button type="danger" plain size="small" @click="deleteMore">批量删除</el-button>
    </div>

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=total
      >
      </el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="datasetDialogVisible" width="35%">
      <el-form label-width="80px" size="small">
        <el-form-item label="鲜花名称">
          <el-input v-model="updateForm.fname" style="width: 60%" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="鲜花进价">
          <el-input v-model="updateForm.mprice" style="width: 40%" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="鲜花售价">
          <el-input v-model="updateForm.sprice" style="width: 40%" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="库存量">
          <el-input v-model="updateForm.cnt" style="width: 30%" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="updateForm.tid" style="width: 30%" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.tid"
                :label="item.tname"
                :value="item.tid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="鲜花图片">
          <el-upload
              v-model="updateForm.img"
              class="avatar-uploader"
              action="http://127.0.0.1:9090/photo/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{ token: token }"
              :auto-upload="true"
          >
            <img v-if="image" :src="image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入描述"
              v-model="updateForm.fdesc"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="赠送对象">
          <el-input v-model="updateForm.obj" style="width: 40%" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="datasetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

 </div>
 
  </div>
</template>

<script>
export default {
  components: {},
  props: {},
  data() {
    return {
      options: [{
        tid: 1,
        tname: '黄金糕'
      }, {
        tid: 2,
        tname: '双皮奶'
      }],
      tid: null,
      // 用于照片uri的存储
      image: null,
      datasetDialogVisible: false,
      title: '',
      updateForm: {
        fid: null,
        fname: null,
        mprice: "",
        sprice: "",
        cnt: null,
        img: '',
        fdesc: '',
        tid: '',
        tname: '',
        obj: '',
      },
      tableData: [],
      form: {},
      fname: '',
      search: "",
      radio: "",
      tname:'',
      type:'',
      currentPage: 1,
      pageSize:10,
      total:0,
      multipleSelection:[],
      dialogImageUrl: '',
      dialogVisible: false,
      // 控制上传鲜花的弹出
      addPhotoVisible: false,
      userInfo:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")):{},
      token: localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")).data.token:{},
    };
  },
  watch: {},
  computed: {},
  methods: {
    getTypes() {
      this.request.get("/type").then(res => {
        if (res.data.code === '200') {
          this.options = res.data.data
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 上传图片的方法
    handleAvatarSuccess(res, file) {
      this.image = URL.createObjectURL(file.raw);
      if (this.addPhotoVisible) {
        this.updateForm.img = res;
      } else if (this.datasetDialogVisible) {
        this.updateForm.img = res;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    displayUpdate(row) {
      this.title = '编辑'
      this.updateForm.fid = row.fid
      this.updateForm.fname = row.fname
      this.updateForm.mprice = row.mprice
      this.updateForm.sprice = row.sprice
      this.updateForm.cnt = row.cnt
      this.updateForm.img = row.img
      this.updateForm.fdesc = row.fdesc
      this.updateForm.tid = row.tid
      this.updateForm.tname = row.tname
      this.updateForm.obj = row.obj
      if (this.updateForm.ddmessage === '-') {
        this.updateForm.ddmessage = ''
      }
      this.datasetDialogVisible = true
    },
    // 新增的弹窗
    add() {
      this.title = '新建'
      this.datasetDialogVisible = true
      this.updateForm = {
        fid: null,
        fname: null,
        mprice: "",
        sprice: "",
        cnt: null,
        img: '',
        fdesc: '',
        tid: '',
        tname: '',
        obj: '',
      }
    },
    // 新增的确定按钮
    save() {
      if (this.updateForm.img === '') {
        this.updateForm.img = null
      }
      this.request.post("/flower", this.updateForm).then(res => {
        console.log(res)
        if (res.data.code === '200') {
          this.$message.success("恭喜小主！保存成功")
          this.datasetDialogVisible = false
          this.load()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 删除
    handleDelete(index, row) {
      console.log(index, row);
      
      this.$confirm('小主！您的操作将在鲜花列表删除该鲜花, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.request.delete('/flower/'+row.fid).then(res=>{
          if(res.data.code ==="200"){
            this.$message.success("已听从您的指示！为您净化空间啦！")
            this.load()
           }
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '还好还好！可以挽回！已为您取消删除该鲜花！'
        });
      });

    },
    // 批量删除
    deleteMore(){
      console.log(this.multipleSelection)
      let ids = this.multipleSelection.map(v =>v.fid)
      console.log(ids)
      this.$confirm('小主！您的操作将在鲜花列表批量删除这些鲜花, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }).then(() => {
      this.request.post('/flower/del/batch',ids).then(res=>{
        if(res.data.code ==="200"){
          this.$message.success("已听从您的指示！为您净化空间啦！")
          this.load()
         }
      })
    }).catch(() => {
      this.$message({
        type: 'warning',
        message: '还好还好！可以挽回！已为您取消删除这些好看的鲜花！'
      });
    });
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },
    // 页面初始化
    load() {
      this.request.get("/flower/page", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            fname:this.fname,
            obj:this.fname
          }
      }).then((res) => {
        let data = res.data.data
        this.tableData = data.records;
        console.log(this.tableData)
        this.pageSize = data.size
        this.currentPage = data.current
        this.total = data.total
        this.pages = data.pages
      });
    },
  //  这是多选的值  multipleSelection(选择的那几行的数据)
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    // 文件列表移除文件时的钩子
    // handleRemove(file, fileList) {
    //   console.log(file, fileList);
    // },
    //    // 点击文件列表中已上传的文件时的钩子
    // handlePictureCardPreview(file) {
    //   console.log(file)
    //   this.dialogImageUrl = file.url;
    //   this.dialogVisible = true;
    // }
  },
  created() {
    this.load()
    this.getTypes()
    console.log("####user")
  },
  mounted() {

  },
};
</script>
<style lang="less" scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.star {

  .compute {
    float: right;
    display: flex;
    // margin-bottom: 5%;
    // position: fixed; 是相对于浏览器窗口固定的。即使窗口滚动。他也不会移动
    position: fixed;
    top:650px;
    right:45px;

    .heji {
      // float: right;
      margin: 13px 50px;
      text-align: center;
      .price {
        color: red;
        font-size: 20px;
      }
    }
    .jiesuan {
      margin: 10px;
    }
  }
  .footer {
  display: flex;
  justify-content:space-between;
  .elbutton {
  padding-top: 15px;
}
.block {
  float: right;
  margin-top: 15px;
}
}

}
</style>